#include "WordMatchesRetriever.h"
#include<string>
#include "DocMatch.h"
#include<fstream>
#include<map>
#include<sstream>
#include <iostream>
#include "LoadCP.h"

using namespace std;
WordMatchesRetriever::WordMatchesRetriever()
{
}

WordMatchesRetriever::~WordMatchesRetriever()
{
}

map<string, DocMatch> WordMatchesRetriever::getWordMatches(uint wordHash, int step)
{
		
	ifstream in;	
	in.open("/work/FinalC.txt", ios::in);
	uint chunksize = 1000000000; 
	map<string,DocMatch> result;
	if(in.is_open())
	{
		unsigned long long offset = LoadCP::getOffset(wordHash,step);
		//cout << "Sai daqui.. SUGAAA!!!!" << endl;
		streamoff dummy = offset;
		//cout << "Offset/Dummy" << offset << "/" << dummy << endl;
		//cout << "Arquivo --> Pos em bytes = " << in.tellg() << endl;
		while(offset > chunksize)
		{
			in.seekg(chunksize,ios_base::cur);
			//cout << "Arquivo --> Pos em bytes = " << in.tellg() << endl;
			offset -=chunksize;
		}
		in.seekg(offset,ios_base::cur);
		//if(in.eofbit || in.failbit || in.badbit)
			//cout << "Deu merda no seek" << endl;
		//cout << "Arquivo --> Pos em bytes = " << in.tellg() << endl;
		uint wordRead;
		string line;
		//in >> line;
		//cout <<"Li a linha:" <<  line << endl;
		in >> wordRead;
		//cout << "Started looking for at: " << wordRead << endl;
		//if(wordRead < 0)
		//	return result;
		while(wordRead < wordHash) // Procurando a palavra
		{
			getline(in,line);
			in >> wordRead;
			//cout << "Peguei linha: " << line << endl;
			//cout << "Tentando palavra: " << wordRead << endl;
			//cout << "Quero: " << wordHash << endl;
		}
		if( wordRead == wordHash) // Achou a palavra
		{
			
			//cout << "A palavra achada no disco eh: " << wordRead << endl;
			stringstream ss;
			string docHash;
			string curPos="";
			getline(in,line);
			ss << line;
			while(!ss.eof() && ss.good())
			{
				ss >> docHash;
				DocMatch dm;
				ss >> curPos;
				while(curPos != ",")
				{
					dm.matches.push_back(static_cast<ushort>(atoi(curPos.c_str())));
					ss >> curPos;
				}
				result[docHash]=dm;
				//cout << "Resultado em: " << docHash << endl;
			}
		}		
	}
	in.close();
	return result;	
}

